package com.yx.front.filter;

import com.alibaba.fastjson.JSON;
import com.yx.front.config.global.BizException;
import com.yx.front.security.LoginUser;
import com.yx.front.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.helper.StringUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author YangXiong
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = httpServletRequest.getHeader("token");
        log.info("===>" + token);
        if (StringUtil.isBlank(token)) {
            doFilter(httpServletRequest, httpServletResponse, filterChain);
            return;
        }
        Claims claims;
        try {
            claims = JwtUtil.parseJwt(token);
        } catch (Exception e) {
            throw new BizException("token非法");
        }
        String userId = claims.getSubject();
        String redisKey = "login:" + userId;
        String user = redisTemplate.opsForValue().get(redisKey);
        LoginUser loginUser = JSON.parseObject(user, LoginUser.class);
        log.info("=====>{}", loginUser);
        if (Objects.isNull(loginUser)) {
            throw new BizException("登录已过期，请重新登录");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //更新redis缓存的TTL
        redisTemplate.opsForValue().set("login:" + userId, JSON.toJSONString(loginUser), 10, TimeUnit.MINUTES);

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
